119. 杨辉三角 II
为保证权益,题目请参考 119. 杨辉三角 II(From LeetCode).
解决方案1
CPP
C++
// LeetCode 119
#include <iostream>
#include <vector>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
vector<int> ans;
vector<int> rightSideView(TreeNode *root) {
ans.clear();
dfs(0, root);
return ans;
}
void dfs(int deepth, TreeNode *root) {
if (root) {
if (ans.size() == deepth) {
ans.push_back(root->val);
} else {
ans[deepth] = root->val;
}
dfs(deepth + 1, root->left);
dfs(deepth + 1, root->right);
}
}
};
int main() {
TreeNode *root1 = new TreeNode(1);
TreeNode *root2 = new TreeNode(2);
TreeNode *root3 = new TreeNode(3);
TreeNode *root4 = new TreeNode(4);
TreeNode *root5 = new TreeNode(5);
root1->left = root2;
root2->right = root5;
root1->right = root3;
root3->right = root4;
Solution so;
for (int x: so.rightSideView(root1)) {
cout << x << endl;
}
return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60